Working with Variables and Naming Conventions in Python
Course: Python Training
Topic: Working with Variables and Naming Conventions
Course Link: Python Training Course
Demo Link: Register for a Course Demo
Website: JustAcademy
1. Introduction to Variables in Python
Variables are fundamental building blocks of Python programming. A variable is a name that refers to an object stored in memory. Programmers use variables to represent data such as numbers, text, Boolean values, collections, and objects created by classes.
Variables make programs easier to understand, maintain, and modify because values can be referenced by meaningful names instead of being repeatedly written directly into the code.
For example:
name = "Rahul"
age = 25
salary = 35000.50
print(name)
print(age)
print(salary)
Output:
Rahul
25
35000.5
In this example, name, age, and salary are variable names. They refer to string and numeric objects, which Python uses when executing the program.
2. Learning Objectives
- Understand variables and how they work in Python.
- Learn how to declare and assign variables.
- Identify valid and invalid variable names.
- Understand Python's naming conventions.
- Work with multiple assignments and variable reassignment.
- Understand dynamic typing and type checking.
- Learn the difference between constants and ordinary variables.
- Apply meaningful naming practices to real-world programs.
- Identify common variable-related errors.
3. What Is a Variable?
A variable is an identifier that refers to an object. When you assign a value to a variable, Python associates the name with that object.
Consider this example:
course = "Python"
duration = 3
is_available = True
Here:
course refers to a string object containing "Python".
duration refers to an integer object containing 3.
is_available refers to a Boolean object containing True.
Unlike languages that require explicit type declarations for ordinary variables, Python determines an object's type at runtime.
4. Creating and Assigning Variables
Python does not require a special keyword such as var or int to create an ordinary variable. Assignment introduces a name in the current scope and binds it to an object.
4.1 Basic Assignment
student_name = "Amit"
marks = 85
percentage = 87.5
print(student_name)
print(marks)
print(percentage)
The equals sign (=) is the assignment operator. It assigns the object produced by the expression on its right to the target name on its left.
4.2 Assignment Is Different from Equality
Assignment and comparison are different operations.
x = 10
print(x == 10)
Output:
True
The first statement assigns the value 10 to x. The second statement checks whether x is equal to 10.
4.3 Assigning Values of Different Types
product = "Laptop"
quantity = 4
price = 54999.99
in_stock = True
print(product, quantity, price, in_stock)
Python supports many built-in data types, including strings, integers, floating-point numbers, Booleans, lists, tuples, dictionaries, and sets.
5. Python Is Dynamically Typed
Python is a dynamically typed language. You do not normally need to declare a variable's type before assigning a value. A name can also be rebound to an object of a different type.
5.1 Example of Dynamic Typing
value = 100
print(value)
print(type(value))
value = "Python Programming"
print(value)
print(type(value))
Output:
100
<class 'int'>
Python Programming
<class 'str'>
Initially, value refers to an integer object. Later, the same name refers to a string object.
Important: Python objects have types even though variable names do not require fixed type declarations. Dynamic typing does not mean that Python ignores types.
6. Rules for Naming Variables in Python
Python follows specific syntax rules for identifiers. A variable name must be valid before Python can execute the statement containing it.
6.1 Variable Naming Rules
- A variable name must begin with a letter or an underscore (
_).
- After the first character, a name may contain letters, digits, and underscores.
- A variable name cannot begin with a digit.
- Spaces are not permitted in variable names.
- Special characters such as
@, #, $, and % cannot be used in ordinary identifiers.
- Python keywords cannot be used as variable names.
- Variable names are case-sensitive.
- Unicode letters are permitted in identifiers, although English letters are often preferred for shared projects.
6.2 Valid and Invalid Variable Names
| Variable Name |
Valid? |
Explanation |
name |
Yes |
Begins with a letter. |
student_age |
Yes |
Uses lowercase letters and an underscore. |
marks2 |
Yes |
Digits are allowed after the first character. |
_count |
Yes |
Identifiers may begin with an underscore. |
total_amount |
Yes |
Uses a descriptive snake_case name. |
2marks |
No |
Begins with a digit. |
student name |
No |
Contains a space. |
first-name |
No |
Contains a hyphen, which is an operator rather than part of an identifier. |
total@price |
No |
Contains an unsupported special character. |
class |
No |
class is a Python keyword. |
for |
No |
for is a Python keyword. |
7. Understanding Case Sensitivity
Python treats uppercase and lowercase letters as different characters in identifiers. Therefore, names that differ only by letter case represent different variables.
name = "Priya"
Name = "Neha"
NAME = "Anjali"
print(name)
print(Name)
print(NAME)
Output:
Priya
Neha
Anjali
Although all three names contain the same letters, Python treats name, Name, and NAME as separate identifiers.
For readability, avoid creating multiple variables that differ only in capitalization unless there is a clear reason to do so.
8. Python Keywords and Reserved Names
Keywords are words reserved by Python syntax. They have specific meanings in the language and cannot be used as ordinary variable names.
Examples include:
if
else
for
while
class
def
return
import
try
except
True
False
None
Attempting to use a keyword as a variable name causes a syntax error.
# Incorrect
class = "Python"
# Correct
course_name = "Python"
You can inspect Python keywords using the keyword module:
import keyword
print(keyword.kwlist)
This displays the keyword list for the Python version you are using.
Names of built-in functions and types, such as list, str, sum, and id, are not all keywords, but using them as variable names is generally discouraged because it hides the original built-ins.
9. Python Naming Conventions
Naming conventions are recommended practices that help programmers create consistent, readable, and maintainable code. Python's commonly followed conventions are described in PEP 8, the official Python style guide.
9.1 Snake Case for Variables
Use lowercase letters with underscores separating words for ordinary variable and function names.
student_name = "Rohit"
total_marks = 450
account_balance = 2500.75
is_logged_in = True
This style is called snake_case.
9.2 Avoid Unclear Names
Short names can be suitable in small loops or mathematical expressions, but descriptive names are usually better for business logic.
# Unclear
x = 500
y = 12
z = x * y
# More descriptive
product_price = 500
quantity = 12
total_cost = product_price * quantity
The second example communicates the purpose of each value without requiring additional explanation.
9.3 Constants Use Uppercase Names
Python does not enforce immutable constants through naming alone. However, PEP 8 recommends uppercase names with underscores for values intended to remain constant throughout a program or module.
PI = 3.14159
MAX_LOGIN_ATTEMPTS = 5
TAX_RATE = 0.18
radius = 7
area = PI * radius ** 2
print(area)
Using uppercase names communicates intent to other developers. It does not prevent reassignment of the variable.
9.4 Class Names Use PascalCase
Class names generally use CapWords, commonly called PascalCase, where each word begins with an uppercase letter.
class StudentRecord:
pass
class BankAccount:
pass
class EmployeeDetails:
pass
By convention, class names are visually distinct from ordinary variable names.
9.5 Leading Underscores
A single leading underscore is a convention indicating that a name is intended for internal use, especially in modules and classes.
_temporary_value = 100
_internal_status = "pending"
A leading underscore does not make a variable truly private. It communicates the intended use of the name.
Names beginning with double underscores inside classes can trigger name mangling. Names with double leading and trailing underscores, such as __init__, are reserved for special language-defined behavior and should not be invented casually.
10. Summary of Naming Conventions
| Element |
Recommended Style |
Example |
| Variables |
snake_case |
student_name |
| Functions |
snake_case |
calculate_total() |
| Classes |
PascalCase / CapWords |
StudentRecord |
| Constants |
UPPER_SNAKE_CASE |
MAX_RETRIES |
| Internal-use names |
Leading underscore |
_internal_value |
| Modules |
Short, lowercase names |
student_utils.py |
| Packages |
Short, lowercase names |
studenttools |
11. Assigning Multiple Variables
Python allows multiple variables to be assigned values in a single statement. This can make simple assignments more concise.
11.1 Multiple Assignment
name, age, city = "Aman", 24, "Mumbai"
print(name)
print(age)
print(city)
Output:
Aman
24
Mumbai
The values are unpacked and assigned to their corresponding names.
11.2 Assigning the Same Value to Multiple Variables
a = b = c = 100
print(a, b, c)
Output:
100 100 100
All three names refer to the same integer object in this example. When using mutable objects, remember that assigning the same object to multiple names does not create independent copies.
11.3 Swapping Variables
Python supports swapping values without a temporary variable.
first = 10
second = 20
first, second = second, first
print(first)
print(second)
Output:
20
10
This feature is useful in sorting algorithms, data processing, and other programming tasks.
12. Reassigning Variables
A variable can be assigned a new value at any time while it is accessible in the current scope. Reassignment changes which object the name refers to.
score = 50
print(score)
score = 75
print(score)
score = score + 10
print(score)
Output:
50
75
85
In the final statement, Python calculates the existing value plus ten and assigns the result back to score.
13. Variables and Data Types
Variables can refer to objects of different built-in data types. Understanding these types helps prevent invalid operations and unexpected results.
| Data Type |
Example |
Description |
| Integer |
age = 25 |
Whole-number values. |
| Float |
price = 99.50 |
Floating-point numeric values. |
| String |
name = "Riya" |
Text represented by a sequence of characters. |
| Boolean |
is_active = True |
Logical values: True or False. |
| List |
marks = [80, 90, 85] |
An ordered, mutable collection. |
| Tuple |
coordinates = (10, 20) |
An ordered, immutable collection. |
| Dictionary |
student = {"name": "Riya"} |
A mapping of keys to values. |
| Set |
numbers = {1, 2, 3} |
A collection of distinct elements. |
13.1 Checking a Variable's Type
Use the built-in type() function to inspect the type of an object.
age = 25
name = "Riya"
price = 99.50
is_active = True
print(type(age))
print(type(name))
print(type(price))
print(type(is_active))
14. Variables and Mutability
Python objects can be mutable or immutable. A mutable object can be changed after creation, while an immutable object cannot be modified in place.
Integers, floats, strings, and tuples are examples of immutable objects. Lists and dictionaries are examples of mutable objects.
14.1 Example with a Mutable List
fruits = ["apple", "banana"]
fruits.append("mango")
print(fruits)
Output:
['apple', 'banana', 'mango']
14.2 Multiple Names Referencing the Same List
first_list = [1, 2, 3]
second_list = first_list
second_list.append(4)
print(first_list)
print(second_list)
Output:
[1, 2, 3, 4]
[1, 2, 3, 4]
Both names refer to the same list object, so a change made through one name is visible through the other.
15. Local and Global Variables
Variable scope determines where a name can be accessed. Local variables are defined within a function, while global variables are defined at the module level.
15.1 Local Variable Example
def greet():
message = "Welcome to Python"
print(message)
greet()
The variable message is local to the function. It cannot normally be accessed by that name outside the function.
15.2 Global Variable Example
course_name = "Python Training"
def display_course():
print(course_name)
display_course()
The function can read the module-level variable because no local variable with the same name shadows it.
15.3 Modifying a Global Variable
count = 0
def increment():
global count
count += 1
increment()
print(count)
Output:
1
The global keyword allows a function to rebind a module-level name. For most application logic, passing values as function arguments and returning results is often easier to test and maintain than relying on mutable global state.
16. Common Variable Naming Mistakes
16.1 Using Reserved Keywords
# Incorrect
for = 10
# Correct
loop_count = 10
Using a keyword as a variable name produces a syntax error.
16.2 Starting a Name with a Number
# Incorrect
1student = "Aman"
# Correct
student1 = "Aman"
16.3 Using Spaces in Names
# Incorrect
student name = "Riya"
# Correct
student_name = "Riya"
16.4 Overwriting Built-in Names
# Avoid
list = [1, 2, 3]
# Prefer
numbers = [1, 2, 3]
Using list as a variable name shadows Python's built-in list() function in the relevant scope. Prefer a descriptive alternative.
16.5 Using Unclear Abbreviations
# Unclear
ta = 4500
# Better
total_amount = 4500
Descriptive names make programs easier for other developers to read and maintain.
17. Type Conversion and Variables
Sometimes a program receives data in one type but needs to perform operations using another. Python provides functions such as int(), float(), and str() for explicit type conversion.
age_text = "25"
age = int(age_text)
price_text = "149.99"
price = float(price_text)
print(age + 5)
print(price)
print(str(age))
Output:
30
149.99
25
Conversions can fail when the input is not suitable. For example, int("hello") raises a ValueError.
18. Practical Example: Student Information System
The following program combines meaningful variable names, multiple data types, calculations, and formatted output.
student_name = "Aarav Sharma"
math_marks = 85
science_marks = 90
english_marks = 88
total_marks = math_marks + science_marks + english_marks
maximum_marks = 300
percentage = (total_marks / maximum_marks) * 100
is_passed = percentage >= 40
print("Student:", student_name)
print("Total Marks:", total_marks)
print("Percentage:", round(percentage, 2))
print("Passed:", is_passed)
Output:
Student: Aarav Sharma
Total Marks: 263
Percentage: 87.67
Passed: True
This example demonstrates how descriptive names improve readability. A reader can easily understand the purpose of each variable and the calculation being performed.
19. Best Practices for Working with Variables
- Choose meaningful names that describe the purpose of the data.
- Use snake_case for variables and functions.
- Use uppercase names for values intended to be constants.
- Avoid Python keywords and unnecessary shadowing of built-in names.
- Keep variable names consistent throughout the project.
- Use names that are descriptive without being unnecessarily long.
- Avoid names that differ only by capitalization.
- Initialize variables before attempting to read them.
- Use type conversion when input data must be interpreted as another type.
- Understand mutable objects and avoid accidental shared-state changes.
- Prefer local variables and function parameters over unnecessary global variables.
- Follow PEP 8 conventions to make code familiar to Python developers.
20. Practice Exercises
Exercise 1: Create Variables
Create variables for your name, age, city, and favorite programming language. Print all four values.
Exercise 2: Identify Valid Names
Decide whether each identifier is valid and explain why:
student_name
2nd_student
total_marks
class
_price
employee@id
marks2026
Exercise 3: Calculate a Total
Create variables for product price and quantity. Calculate and display the total cost.
Exercise 4: Swap Two Values
Assign two numbers to variables and swap them using Python's multiple-assignment feature.
Exercise 5: Apply Naming Conventions
Rewrite these names using appropriate Python naming conventions:
StudentName
totalMarks
MAXIMUMprice
employee salary
Exercise 6: Build a Student Marks Program
Create variables for three subject marks, calculate the total and average, and display the results using descriptive variable names.
21. Interview Questions and Answers
Q1. What is a variable in Python?
A variable is a name that refers to an object. It allows a program to access and work with data through a meaningful identifier.
Q2. Does Python require variable declarations?
No. Python normally creates or binds a variable name through assignment without requiring an explicit type declaration.
Q3. What is dynamic typing?
Dynamic typing means that Python determines object types at runtime, and a variable name can be rebound to objects of different types.
Q4. What are the rules for naming variables?
Names must begin with a letter or underscore, may contain letters, digits and underscores afterward, cannot contain spaces, and cannot be Python keywords.
Q5. What is snake_case?
Snake_case is a naming style that uses lowercase words separated by underscores, such as student_name.
Q6. What is the difference between a variable and a constant?
A variable name can be rebound to another object. A constant is a value intended to remain unchanged by convention; Python does not enforce ordinary constants merely because their names are uppercase.
Q7. Are Python variable names case-sensitive?
Yes. For example, age and Age are different identifiers.
Q8. Can a variable name begin with an underscore?
Yes. An identifier can begin with an underscore. A leading underscore commonly indicates that a name is intended for internal use.
Q9. What happens if a variable is used before assignment?
If the name has not been defined in an accessible scope, Python typically raises a NameError. Reading an unassigned local variable can raise an UnboundLocalError.
Q10. Why should built-in names be avoided as variable names?
Reusing names such as list, str, or sum can hide the corresponding built-in functions or types and make code confusing.
22. Quick Revision Checklist
- A variable name refers to an object.
- The assignment operator is
=.
- Python is dynamically typed.
- Identifiers are case-sensitive.
- Variable names cannot begin with digits.
- Python keywords cannot be used as ordinary variable names.
- Use snake_case for variables and functions.
- Use PascalCase for classes.
- Use UPPER_SNAKE_CASE for intended constants.
- Use
type() to inspect an object's type.
- Understand assignment, reassignment, scope, and mutability.
- Follow PEP 8 for consistent, readable code.
23. Conclusion
Variables allow Python programs to store references to data, perform calculations, process user input, and manage application state. Understanding assignment, dynamic typing, naming rules, scope, and mutability helps developers write reliable programs.
Following consistent naming conventions such as snake_case for variables, PascalCase for classes, and uppercase names for intended constants improves code readability and teamwork. Practicing these concepts provides a strong foundation for learning Python operators, conditional statements, loops, functions, data structures, and object-oriented programming.
Learn Python with JustAcademy
Explore Python training resources and continue building your programming skills through structured learning and hands-on practice.
Python Training Course: Explore the Python Course
Course Demo: Register for a Course Demo
Official Website: Visit JustAcademy